import shutil
import sys
import os
import traceback
import json
import time

from PyQt6.QtGui import QColor, QIcon, QPixmap, QPalette, QBrush
from PyQt6.QtWidgets import (
    QMainWindow, QApplication, QGraphicsDropShadowEffect, QDialog, QVBoxLayout,
    QLabel, QWidget, QMessageBox, QFileDialog
)
from PyQt6.QtCore import (
    Qt, QUrl, QPropertyAnimation, QEasingCurve, QVariantAnimation, QPoint, QSize, QEvent,
    QThread, pyqtSignal
)

from UI.SSDDCleanerWindow import Ui_MainWindow
from calculator.data_cleaner import clean_pti_ssdd, clean_pega_ssdd


if hasattr(sys, '_MEIPASS'):
    current_dir = sys._MEIPASS
else:
    current_dir = "."
json_file_path = os.path.join(current_dir, "conf", "path.json")


# ---------------- Worker线程 ----------------
class CleanerWorker(QThread):
    progress = pyqtSignal(str)   # 用于输出进度信息
    finished = pyqtSignal()      # 完成信号
    error = pyqtSignal(str)      # 错误信号

    def __init__(self, input_folder, output_folder):
        super().__init__()
        self.input_folder = input_folder
        self.output_folder = output_folder

    def run(self):
        try:
            self.progress.emit("开始清理 PTI SSDD 文件...")
            clean_pti_ssdd(self.input_folder, self.output_folder)
            self.progress.emit("PTI SSDD 文件清理完成。")

            self.progress.emit("开始清理 PEGA SSDD 文件...")
            clean_pega_ssdd(self.input_folder, self.output_folder)
            self.progress.emit("PEGA SSDD 文件清理完成。")

            self.finished.emit()
        except Exception as e:
            tb = traceback.format_exc()
            self.error.emit(f"执行出错: {e}\n{tb}")


# ---------------- 主窗口 ----------------
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.output_folder = None
        self.input_folder = None
        self.setupUi(self)

        self.setWindowIcon(QIcon('UI/icon002.ico'))

        # 设置背景图片，自动拉伸填充
        self.bg_pixmap = QPixmap("UI/background.png")
        self.init_settings()
        self.init_signals()

        self.worker = None  # 保存线程对象


    def resizeEvent(self, event):
        scaled_bg = self.bg_pixmap.scaled(
            self.size(),
            Qt.AspectRatioMode.IgnoreAspectRatio,
            Qt.TransformationMode.SmoothTransformation
        )
        palette = QPalette()
        palette.setBrush(QPalette.ColorRole.Window, QBrush(scaled_bg))
        self.setPalette(palette)
        super().resizeEvent(event)

    def closeEvent(self, event):
        """关闭窗口事件处理"""
        # 如果后台线程正在运行，提示用户是否终止
        if self.worker and self.worker.isRunning():
            reply = QMessageBox.question(
                self,
                "正在处理数据",
                "当前有数据处理任务正在执行，是否要终止并关闭窗口？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.Yes:
                # 强制终止线程
                self.worker.terminate()
                self.worker.wait()
            else:
                event.ignore()
                return

        # 保存路径信息
        path_dict = {
            "input_folder": self.input_folder,
            "output_folder": self.output_folder
        }
        try:
            with open(json_file_path, 'w', encoding='utf-8') as f:
                json.dump(path_dict, f, ensure_ascii=False, indent=4)
        except Exception as e:
            print(f"保存路径失败: {e}")

        event.accept()

    def init_settings(self):
        self.statusbar.setStyleSheet("color: white;")
        self.load_paths()
        self.load_input_files()

    def init_signals(self):
        self.pushButton.clicked.connect(self.select_input_folder)
        self.pushButton_2.clicked.connect(self.select_output_folder)
        self.pushButton_3.clicked.connect(self.change_input_file)
        self.pushButton_4.clicked.connect(self.load_input_files)
        self.pushButton_5.clicked.connect(self.start_processing)

    # ---------------- 核心执行入口 ----------------
    def start_processing(self):
        if not self.input_folder or not self.output_folder:
            QMessageBox.warning(self, "警告", "请先选择输入和输出文件夹！")
            return

        # 禁用按钮，防止重复点击
        self.pushButton_5.setEnabled(False)

        # 创建后台线程
        self.worker = CleanerWorker(self.input_folder, self.output_folder)
        self.worker.progress.connect(self.on_progress)
        self.worker.finished.connect(self.on_finished)
        self.worker.error.connect(self.on_error)
        self.worker.start()

        QMessageBox.information(self, "提示", "任务已开始，后台处理中...")

    # ---------------- 信号槽处理 ----------------
    def on_progress(self, message):
        print(message)  # 可以改成在界面上显示，比如 self.label.setText(message)
        self.update_status(message)

    def on_finished(self):
        QMessageBox.information(self, "完成", "所有清理任务已完成！")
        self.pushButton_5.setEnabled(True)

    def on_error(self, message):
        QMessageBox.critical(self, "错误", message)
        self.pushButton_5.setEnabled(True)


    def update_status(self, message):
        """更新状态栏信息"""
        self.statusbar.showMessage(message)


    def load_paths(self):
        """加载保存的路径"""
        try:
            if os.path.exists(json_file_path):
                with open(json_file_path, 'r', encoding='utf-8') as f:
                    path_dict = json.load(f)
                    print(path_dict)
                    self.input_folder = path_dict.get("input_folder", "")
                    self.output_folder = path_dict.get("output_folder", "")
                    self.lineEdit.setText(self.input_folder)
                    self.lineEdit_2.setText(self.output_folder)
        except Exception as e:
            print(f"加载路径失败: {e}")

    def select_input_folder(self):
        """选择输入文件夹"""

        self.input_folder = QFileDialog.getExistingDirectory(self, "Destination for cleaned files", "")
        if self.input_folder:
            self.lineEdit.setText(self.input_folder)


    def select_output_folder(self):
        """选择输出文件夹"""
        self.output_folder = QFileDialog.getExistingDirectory(self, "Destination for TKM Metrics", "")
        if self.output_folder:
            self.lineEdit_2.setText(self.output_folder)

    def change_input_file(self):
        pti_folder = os.path.join(self.input_folder, "PTI")
        pega_folder = os.path.join(self.input_folder, "Pega")

        # 确保目录存在
        os.makedirs(pti_folder, exist_ok=True)
        os.makedirs(pega_folder, exist_ok=True)

        # 打开文件选择对话框
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择Excel文件",
            "",
            "Excel Files (*.xls *.xlsx)"
        )

        if not file_path:
            return  # 用户取消选择

        file_name = os.path.basename(file_path)

        # 判断关键字
        if "PTI_SSDD" in file_name:
            target_folder = pti_folder
        elif "PEGA_SSDD" in file_name:
            target_folder = pega_folder
        else:
            QMessageBox.critical(self, "错误", "文件名必须包含 'PTI_SSDD' 或 'PEGA_SSDD'")
            return

        # 清理目标目录
        for f in os.listdir(target_folder):
            f_path = os.path.join(target_folder, f)
            if os.path.isfile(f_path):
                os.remove(f_path)

        # 拷贝文件
        try:
            shutil.copy(file_path, target_folder)
            QMessageBox.information(self, "成功", f"文件已复制到 {target_folder}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"复制文件失败: {e}")

        self.load_input_files()


    def load_input_files(self):
        
        # 清空frame_2中的内容
        layout = self.frame_2.layout()
        if layout is None:
            layout = QVBoxLayout()
            self.frame_2.setLayout(layout)
        else:
            # 清除所有现有控件
            for i in reversed(range(layout.count())): 
                item = layout.itemAt(i)
                if item.widget():
                    item.widget().setParent(None)
                else:
                    # 删除非widget项目（如spacer等）
                    layout.removeItem(item)
        
        pti_folder = os.path.join(self.input_folder, "PTI")
        pega_folder = os.path.join(self.input_folder, "Pega")
        
        # 添加PTI标签
        pti_label = QLabel("PTI Files:")
        pti_label.setStyleSheet("font-weight: bold; color: white; font-size: 16px;")
        layout.addWidget(pti_label)
        
        # 获取PTI文件夹中的Excel文件
        if os.path.exists(pti_folder):
            pti_files = [f for f in os.listdir(pti_folder) if f.endswith(('.xlsx', '.xls', 'XLSX', 'XLS'))]
            for file in pti_files:
                file_label = QLabel(f"  • {file}")
                file_label.setStyleSheet("color: white; font-size: 14px; padding: 2px 0px 2px 10px;")
                layout.addWidget(file_label)
        else:
            no_pti_label = QLabel("  No PTI folder found")
            no_pti_label.setStyleSheet("color: white; font-size: 14px; padding: 2px 0px 2px 10px;")
            layout.addWidget(no_pti_label)
            
        # 添加间隔
        layout.addSpacing(10)
        
        # 添加Pega标签
        pega_label = QLabel("Pega Files:")
        pega_label.setStyleSheet("font-weight: bold; color: white; font-size: 16px;")
        layout.addWidget(pega_label)
        
        # 获取Pega文件夹中的Excel文件
        if os.path.exists(pega_folder):
            pega_files = [f for f in os.listdir(pega_folder) if f.endswith(('.xlsx', '.xls'))]
            for file in pega_files:
                file_label = QLabel(f"  • {file}")
                file_label.setStyleSheet("color: white; font-size: 14px; padding: 2px 0px 2px 10px;")
                layout.addWidget(file_label)
        else:
            no_pega_label = QLabel("  No Pega folder found")
            no_pega_label.setStyleSheet("color: white; font-size: 14px; padding: 2px 0px 2px 10px;")
            layout.addWidget(no_pega_label)




if __name__ == '__main__':

    def excepthook(exc_type, exc_value, exc_tb):
        """全局异常处理钩子"""
        # 打印到控制台
        print(f"未捕获的异常: {exc_type.__name__}: {exc_value}")
        traceback.print_tb(exc_tb)

        # 如果有logger，记录到日志
        try:
            if 'window' in globals() and hasattr(window, 'logger'):
                window.logger.error(f"未捕获的异常: {exc_type.__name__}: {exc_value}")
                window.logger.error("".join(traceback.format_tb(exc_tb)))
        except:
            pass

        # 显示错误对话框（可选）
        try:
            error_msg = f"{exc_type.__name__}: {exc_value}"
            QMessageBox.critical(None, "未处理的错误",
                                 f"程序发生未处理的错误:\n{error_msg}\n")
        except:
            pass
    # 设置全局异常处理钩子
    sys.excepthook = excepthook

    try:
        app = QApplication(sys.argv)
        # 切换到浅色主题
        window = MainWindow()
        window.show()
        sys.exit(app.exec())
    except Exception as e:
        print(f"程序启动失败: {e}")
        traceback.print_exc()
        QMessageBox.critical(None, "启动错误", f"程序启动失败:\n{e}")
        sys.exit(1)
